package com.zhenhe.core.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhenhe.core.common.global.Global;


/**
 * @description 短信接口
 * @author 朱华剑
 * @date 2015年10月14日下午8:16:21
 */
public class SMSUtil {
	
	private static final Logger log = LoggerFactory.getLogger(SMSUtil.class);
	
	private static final String URL = "http://utf8.sms.webchinese.cn/?";
	
	
	/**
	 * @description 中国网建短信通
	 * 返回值说明
	 * -1	没有该用户账户
	 * -2	接口密钥不正确 [查看密钥]，不是账户登陆密码
	 * -21	MD5接口密钥加密不正确
	 * -3	短信数量不足
	 * -11	该用户被禁用
	 * -14	短信内容出现非法字符
	 * -4	手机号格式不正确
	 * -41	手机号码为空
	 * -42	短信内容为空
	 * -51	短信签名格式不正确，接口签名格式为：【签名内容】
	 * -6	IP限制
	 * 大于0	短信发送数量
	 * @return
	 * @author 朱华剑
	 * @throws IOException 
	 * @throws HttpException 
	 * @date 2015年10月14日下午8:16:04
	 */
	public static boolean webChineseSMS(String Uid,String Key,String smsMob, String smsText){
		boolean b = false;
		try {
			smsText=URLEncoder.encode(smsText,"utf-8");
		} catch (UnsupportedEncodingException e) {
		}
		StringBuffer url = new StringBuffer(URL);
		url.append("Uid=").append(Uid);
		url.append("&Key=").append(Key);
		url.append("&smsMob=").append(smsMob);
		url.append("&smsText=").append(smsText);
		try {
			HttpClient httpclient = HttpClients.createDefault();
			HttpGet get = new HttpGet(url.toString());	
			HttpResponse execute = httpclient.execute(get);
			if(execute.getStatusLine().getStatusCode()==200){
				String resp = EntityUtils.toString(execute.getEntity());
				Integer result = Integer.valueOf(resp);
				if(result>0){
					log.info("发送短信成功，号码{},发送条数{}",smsMob,result);
					b=true;
				}else{
					log.warn("发送短信失败,错误码{},url={}",result,url );
				}
			}else{
				log.warn("发送短信失败，返回码{},url={}", execute.getStatusLine().getStatusCode(),url.toString());
			}
			
			
		} catch (Exception e) {
			log.error("发送短信出错,url={}",url);
			log.error("发送短信出错",e);
		}
		return b;
	}
	
	/**
	 * 
	 * @param callphone 号码
	 * @param content 内容
	 */
	public static boolean webChineseSMS(String callphone,String content){
		String Uid = Global.getConfig("sms.wangjian.uid");
		String Key = Global.getConfig("sms.wangjian.key");
		return webChineseSMS(Uid, Key, callphone, content);
	}
	
	
	
	
	
	
	/**
	 * @description 短信发送测试
	 * @param args
	 * @author 朱华剑
	 * @date 2015年10月14日下午8:43:24
	 */
	public static void main(String[] args){
		boolean b1 = webChineseSMS("电话号码", "内容");
		System.out.println(b1);
//		
//		boolean b2 = FoomeiSMS("17712623306", "验证码:8888");
//		System.out.println(b2);
		
//		boolean b3 = shouyiXinxiSMS( "17712623306", "验证码:8888");
//		System.out.println(b3);
	}
}

